package com.rt.java.util.concurrent;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

// 等待通知机制(交替打印)
public class ConditionDemo {
    static AtomicInteger ai = new AtomicInteger(0);

    public static void main(String[] args) {
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition condition = reentrantLock.newCondition();
        new Thread(() -> {
            while (ai.get() < 100) {
                reentrantLock.lock();
                try {
                    while (ai.get() % 2 == 0) {
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("奇 =>" + ai.getAndIncrement());
                    condition.signal();
                } finally {
                    reentrantLock.unlock();
                }

            }
        }).start();

        new Thread(() -> {
            while (ai.get() < 100) {
                reentrantLock.lock();
                try {
                    while (ai.get() % 2 == 1) {
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("偶 =>" + ai.getAndIncrement());
                    condition.signal();
                } finally {
                    reentrantLock.unlock();
                }

            }
        }).start();
    }
}
